/*
 * The LevelDB-CLI Project
 * Copyright (C) 2024 JuRuoqwq<BitPasta@163.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "run_cmd.h"
#include "command_line.h"

#include <iostream>

int main(int argc, const char *argv[])
{
    CommandLine cli;
    cli.PrintHello();
    RunCmd runCmd;
    // 解析arguments
    if (argc != 1) {
        // 要打开文件
        // 命令的含义详见文档
        std::string currentArg;
        bool isExistOnly = false;
        std::string dbName;
        int status = 0; // 用于防止在错误后仍然输出OK
        for (int i = 1; i < argc; i++) {
            currentArg = (std::string)argv[i];
            if (currentArg == "--exist-only") {
                // 当有此flag时，只打开存在的DB，即create_if_missing = false
                isExistOnly = true;
            } else if (currentArg == "-o" || currentArg == "--open") {
                // 防止-o结尾的情况
                if (i + 1 == argc) {
                    std::cerr << "Missing database name atfer argument \"-o\"!" << std::endl;
                    std::cerr << "Type \"help\" for more information!" << std::endl;
                    status = -1;
                } else {
                    dbName = (std::string)argv[i + 1];
                    ++i; // 跳过数据库所在的索引
                }
            } else {
                std::cerr << "Invalid option \"" << currentArg << "\"!" << std::endl;
                std::cerr << "Type \"help\" for more information!" << std::endl;
            }
        }
        if (isExistOnly == false && status == 0) {
            runCmd.Run("opts create_if_missing true");
        }
        if (dbName != "") {
            // 示例：leveldb_cli --exist-only
            runCmd.Run("open " + dbName);
        }
    }

    while (true) {
        cli.PrintPrompt();
        std::string command = cli.GetCommand();
        runCmd.Run(command);
    }
}